import React, { useEffect, useState } from 'react';
import { Button, Container, Dropdown, Form, InputGroup, ListGroup, ListGroupItem } from 'react-bootstrap';
import DropdownItem from 'react-bootstrap/esm/DropdownItem';
import { useLocation, useNavigate } from 'react-router';
import appSetting from '../../store/AppSetting';
import MaterialType from './MaterialType';

interface MaterialEditProps{}
interface MaterialEditState{
    file:File
}

const MaterialEdit:React.FC = (props:MaterialEditProps,state:MaterialEditState)=>{

    const [mType,setMType] = useState("image");;
    
    const [mName,setMName] = useState("图片");

    const [file,setFile] = useState<File>();

    const [kind,setKind] = useState("tem");

    const [requirement,setRequirement] = useState<string>();
    const [materialTitle,setMaterialTitle] = useState("Default Title")
    const [materialDescription,setMaterialDescription] = useState("Default Description")
    const requirementConfig:any = {
        'image':"bmp/png/jpeg/jpg/gif",
        'audio':"mp3/wma/wav/amr",
        "video":"MP4",
        "thumb":"jpg"
    }
    const location = useLocation();

    useEffect(()=>{
        let k = (new URLSearchParams(location.search)).get("type");
        if(k){
            setKind(k);
        }
    },[])

    const onSelectOption:any= (eventKey:string,e:any)=> {
        setMType(eventKey);
        setRequirement(requirementConfig[eventKey]);
        switch(eventKey){
            case "image":{
                setMName("图片")
                break;
            }
            case "audio":{
                setMName("音频")
                break;
            }
            case "video":{
                setMName("视频")
                break;
            }
            case "thumb":{
                setMName("缩略图")
                break;
            }
        }
    }

    return (<Container>
        <h1>{kind}素材</h1>
        <Dropdown onSelect={onSelectOption} defaultValue={0}>
            <Dropdown.Toggle variant="success" id="dropdown-basic">
                {mName}
            </Dropdown.Toggle>
        <Dropdown.Menu>
            <Dropdown.Item eventKey={"image"}>图片</Dropdown.Item>
            <Dropdown.Item eventKey={"audio"}>音频</Dropdown.Item>
            <Dropdown.Item eventKey={"video"}>视频</Dropdown.Item>
            <Dropdown.Item eventKey={"thumb"}>缩略图</Dropdown.Item>
        </Dropdown.Menu>

        </Dropdown>
        <Form method='POST' action=''>
            <Form.Group>
                <Form.Label htmlFor='#fileTitle'></Form.Label>
                <Form.Control type='input'id="fileTitle" placeholder='文件标题'
                onChange={(e)=>{
                    setMaterialTitle(e.currentTarget.value);
                }}
                />
                <Form.Label htmlFor='#fileDesc'></Form.Label>
                <Form.Control type='input'id="fileDesc" placeholder='文件描述' 
                onChange={(e)=>{
                    setMaterialDescription(e.currentTarget.value);
                }}
                />
                <Form.Label htmlFor='#fileControl'>格式要求:&nbsp;{requirement}</Form.Label>
                <Form.Control type='file' id="fileControl" name='' onChange={(e)=>{
                    let inputControl = e.currentTarget as HTMLInputElement;
                    let f  = inputControl.files && inputControl.files[0];
                    if(f != null){
                        setFile(f);
                    }
                }}/>
                <Button variant="primary" style={{marginTop:20}} onClick={()=>{
                    if(!file){
                        return;
                    }
                    // let url = `/wxproxy/cgi-bin/media/upload?access_token=${appSetting.accessToken}&type=${mType}`;
                    // if(kind === 'per'){
                       let url = `/wxproxy/cgi-bin/material/add_material?access_token=${appSetting.accessToken}&type${mType}`;
                    // }
                    var formData = new FormData();
                    if(file){
                        const filetype = file.name.split('.').pop()||""
                        if(mType === 'image' && (!['png','jpg','jpeg','gif','bmp'].includes(filetype))){
                            alert("图片格式不对");
                            return;
                        }
                        if(mType === 'audio' && (!['mp3','wma','wav','amr'].includes(filetype))){
                            alert("音频格式不对");
                            return;
                        }
                        if(mType === 'video' && (!["MP4"].includes(filetype.toUpperCase()))){
                            alert("视频格式不对");
                            return;
                        }
                        if(mType === 'thumb' && (!["jpg"].includes(filetype.toLowerCase()))){
                            alert("缩略图格式不对");
                            return;
                        }
                        formData.append("media",file,file?.name);
                        if(!materialTitle || materialTitle.length === 0){
                            alert("请输入文件标题");
                        }
                        if(!materialDescription || materialDescription.length === 0){
                            alert("请输入文件描述");
                        }
                        if(kind === 'per'){
                            formData.append("description",JSON.stringify({
                                "title":materialTitle,
                                "introduction":materialDescription}));
                        }
                    }
                    fetch(url,{
                        method:"POST",
                        body:formData
                    }).then(res=>res.json()).then((jsonResp={})=>{
                        console.log(JSON.stringify(jsonResp));
                        alert(JSON.stringify(jsonResp));
                    }).catch((err)=>{
                        alert(JSON.stringify(err));
                    })
                }}>Submit</Button>
            </Form.Group>
        </Form>
    </Container>)
}

export default MaterialEdit;